package pl.us.ij.plugins.segmentation.commands.edges;

import ij.process.FloatProcessor;
import ij.process.ImageProcessor;
import pl.us.ij.plugins.segmentation.infrastructure.Command;
import pl.us.ij.plugins.segmentation.infrastructure.exceptions.BreakCommandException;

import static pl.us.ij.plugins.segmentation.commands.edges.SkeletonCommand.overlapMask;

/**
 * Created by IntelliJ IDEA.
 * User: Przemek
 * Date: 2010-01-10
 * Time: 19:49:11
 * To change this template use File | Settings | File Templates.
 */
public class BranchCuttingCommand extends Command<SkeletonCommandParams> {
    @Override
    protected void processImage(FloatProcessor fp) throws BreakCommandException {
        int width = fp.getWidth();
        int height = fp.getHeight();

        ImageProcessor ip = fp;

        SkeletonCommandParams params = getParams();

        float[] pixels = (float[]) ip.getPixels();

//        negative(pixels);
        int zeroCount = 0;

        for ( int i = 0; i < params.getIterationCount() || params.isAuto(); i++ ) {

            float[] flatMask1 = {255, 2, 2,
                    255, 0, 2,
                    255, 255, 255};
            overlapMask(width, height, pixels.clone(), pixels, flatMask1, 255);
            float[] flatMask2 = {255, 255, 255,
                    255, 0, 2,
                    255, 2, 2};
            overlapMask(width, height, pixels.clone(), pixels, flatMask2, 255);
            float[] flatMask3 = {255, 255, 255,
                    2, 0, 255,
                    2, 2, 255};
            overlapMask(width, height, pixels.clone(), pixels, flatMask3, 255);
            float[] flatMask4 = {2, 2, 255,
                    2, 0, 255,
                    255, 255, 255};
            overlapMask(width, height, pixels.clone(), pixels, flatMask4, 255);

            if ( params.isAuto() ) {
                int currentZeroCount = countPixels( pixels );
                if ( currentZeroCount == zeroCount )
                    break;
                zeroCount = currentZeroCount;
            }

            if ( ij.IJ.escapePressed() ) {
                break;
            }
        }
//        negative(pixels);

//        getImageProcessor().setPixels(0, (FloatProcessor) ip);
    }

        private int countPixels(float[] pixels) {
        int zeroCount = 0;
        for ( int i = 0; i < pixels.length; i++ ) {
            if ( pixels[ i] == 0 ) {
                zeroCount++;
            }
        }

        return zeroCount;
    }
}
